--
-- @Author:      feilong
-- @DateTime:    2019-10-30 23:05:48
-- @Description: 日记记录
-- log文件按进程名按天生成


local skynet = require "skynet"
local lfs = require "lfs"

local maxsize = 50 *1024*1024 --文件最大M，超过会分割

local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch)

	self.message_dispatch = message_dispatch	
	self.file = nil --文件句柄
	self.server_name = skynet.getenv("server_name") --节点名
	self.suffix = ".log" --文件后缀
    self.date = self:getDate()
	self.file_name = self.server_name.."_"..self.date --文件名
	self.path = "/home/logs/"
    self.date_path = self.path .. self.date .."/"
    lfs.mkdir(self.path)
    lfs.mkdir(self.date_path)
	self:register()	
end

--注册本服务里的消息
function MessageHandler:register()

	-- self.message_dispatch:registerSelf('start',handler(self,self.start))
end

function MessageHandler:getDate( ... )
	return os.date("%Y_%m_%d",os.time())
end

--打开一个文件， 但不关闭
function MessageHandler:checkFile()
    local date = self:getDate()
    if self.date ~= date then 
        self.date = date
        self.date_path = self.path .. self.date .."/"
        lfs.mkdir(self.date_path)
        if self.file then 
            self.file:close()
            self.file = nil
        end
    end
    if self.file then 
        return
    end
    local file_name = self.date_path .. self.file_name .. self.suffix   
    self.file = io.open(file_name, "a+")
end

--保存到文件
function MessageHandler:saveData(msg)
    if not msg and not next(msg) then
    	return 
    end    
    self:checkFile()

	local data = msg.."\n"
	self.file:write(data)
	self.file:flush()
	local file_size = self.file:seek("end")
	if file_size >= maxsize then
		--分割文件			
		local sub_time = os.date("%H_%M_%S",os.time())	
        local file_name = self.date_path .. self.file_name .. self.suffix   
		local rename = self.date_path .. self.file_name .."_"..sub_time .. self.suffix
		self.file:close()
		self.file = nil			
		os.rename(file_name, rename)
	end						
end


---------------------------------------------------------
-- CMD
---------------------------------------------------------





return MessageHandler